<?php
/**
 * Author: Traveler
 * Time  : 2021/8/31 16:33
 */

namespace app\controller\crm\v1;


use app\ErrorCode;
use app\service\MainService;
use sunshine\basic\BaseController;
use sunshine\exceptions\ApiException;
use think\App;
use think\exception\ValidateException;
use think\Response;

class Main extends BaseController
{
    /**
     * Main constructor.
     *
     * @param App         $app
     * @param MainService $service
     */
    public function __construct(App $app, MainService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 登陆后的用户信息和菜单权限
     *
     * @return Response
     */
    public function getProfile(): Response
    {
        if (!isset($this->request->tokenPayload['uid'])) {
            throw new ApiException(ErrorCode::MISSING_PARAMETERS);
        }

        $id = $this->request->tokenPayload['uid'];

        return $this->json->api(ErrorCode::SUCCESS, $this->service->getMainProfile($id));
    }

    /**
     * 获取公司相关统计信息
     *
     * @return Response
     */
    public function getCompanyStatistics(): Response
    {
        return $this->json->api(ErrorCode::SUCCESS, $this->service->getCompanyStatistics());
    }

    /**
     * 获取网吧相关统计信息
     *
     * @return Response
     */
    public function getIcafeStatistics(): Response
    {
        return $this->json->api(ErrorCode::SUCCESS, $this->service->getIcafeStatistics());
    }


    /**
     * 修改当前登陆员工的密码
     *
     * @return Response
     */
    public function changePassword(): Response
    {
        if (!isset($this->request->tokenPayload['uid'])) {
            throw new ApiException(ErrorCode::MISSING_PARAMETERS);
        }

        $id = $this->request->tokenPayload['uid'];
        $data = $this->request->put();

        try {
            $this->validate($data, 'PasswordValidate');
        } catch (ValidateException $e) {
            throw new ApiException($e->getError());
        }

        if (!$this->service->changePassword($id, $data)) {
            throw new ApiException(ErrorCode::UPDATE_FAILED);
        }

        return $this->json->api(ErrorCode::SUCCESS);
    }
}
